/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.zhangtai.oss;

import com.aliyun.oss.OSSClient;


import com.zhangtai.exception.RException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AliyunCloudStorageService extends CloudStorageService {


    private String aliyunEndPoint="http://oss-cn-shenzhen.aliyuncs.com";


    private String aliyunAccessKeyId="LTAI1Prvin3YSfKv";


    private String aliyunAccessKeySecret="MZA4OVRal7cN03lYi1uHeVxZ4okYVE";

    @Value("${ossUpload.aliyunBucketName}")
    private String aliyunBucketName;

    //http://taicaifu.oss-cn-shenzhen.aliyuncs.com
    @Value("${ossUpload.aliyunDomain}")
    private String aliyunDomain;


    @Value("${ossUpload.aliyunPrefix}")
    private String aliyunPrefix;

    private OSSClient client;

    public AliyunCloudStorageService(){

        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(aliyunEndPoint, aliyunAccessKeyId,
                aliyunAccessKeySecret);
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(aliyunBucketName, path, inputStream);
        } catch (Exception e){
            throw new RException("上传文件失败，请检查配置信息", e);
        }
//
        return aliyunDomain + "/" + path;

    }



    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(aliyunPrefix, suffix));
    }

    public String uploadSuffix(byte[] data,String catlog, String suffix) {
        return upload(data, getPath2(aliyunPrefix, catlog,suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(aliyunPrefix, suffix));
    }


    public String uploadSuffix(InputStream inputStream,String catlog, String suffix) {
        return upload(inputStream, getPath2(aliyunPrefix,catlog, suffix));
    }

    @Test
    public void test() throws FileNotFoundException {
        AliyunCloudStorageService storageService = new AliyunCloudStorageService();

        File file = new File("D:\\logo_kitty_blue.png");


        FileInputStream fileInputStream = new FileInputStream(file);

        MultipartFile a= (MultipartFile) file;
        String aaa = storageService.uploadSuffix(fileInputStream,"abc.png");
        System.out.println(aaa);
    }
}
